package com.dream21th.dream21thredis.service;

import java.util.stream.IntStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.dream21th.dream21thredis.annotation.RedisDisLock;
import com.dream21th.dream21thredis.lock.RedisLock;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class RedisLockService {

	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;

	private static String key = "lock-test";
	
	private static int count=10;

	public void test() {
		RedisLock lock = new RedisLock(redisTemplate, key, 10000, 20000);
		try {
			if (lock.lock()) {
				log.info(Thread.currentThread().getName()+"------>>>>begin");
				Thread.sleep(1000);
				if(count>=1){
					count--;
					log.info("count:{}",count);	
				}
				log.info(Thread.currentThread().getName()+"------>>>>end");
			}

		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			// 为了让分布式锁的算法更稳键些，持有锁的客户端在解锁之前应该再检查一次自己的锁是否已经超时，再去做DEL操作，因为可能客户端因为某个耗时的操作而挂起，
			// 操作完的时候锁因为超时已经被别人获得，这时就不必解锁了.
			if(!lock.isExpired()){
				lock.unlock();
			}
			
		}
	}
	
	@RedisDisLock(prefix="test",key="#{i}",timeoutMsecs=60*1000)
	public void desc(String i){
		if(count>0){
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			count--;
			log.info("-------------------------->>>>{}",count);
		}else{
			log.info("-------------------------->>>>{}","已经没有货了");
		}
		
	}
	
	
	public void run(){
		IntStream.range(0, 100).forEach(i->{
			Thread run=new Thread(new Runnable() {
				@Override
				public void run() {
					test();
				}
			});
			run.start();
		});
	}
}
